package club.hicode.daydayup.netty.udp.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.IOException;

/**
 * @author leizhenyang
 */
public class UDPServer {

    private static final String DELIMITER = "$";

    public void run(int port) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(" delimiter", new DelimiterBasedFrameDecoder(1024 * 8, Unpooled.copiedBuffer(DELIMITER.getBytes())));
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());//如果需要发送结果必须在这个加入解码器
                            pipeline.addLast("xx", new UDPServerHandler());
                        }
                    })
                    .bind(port).sync().channel().closeFuture().await();
        } catch (Exception e) {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws IOException {
        new UDPServer().run(19876);
        System.in.read();
    }
}
